<?php

namespace app\admin\controller\classes;

use app\common\controller\Backend;
use fast\Tree;
use fast\Random;
use think\Db;
use think\exception\DbException;
use think\response\Json;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Teachers extends Backend
{
    protected $noNeedRight = ['*'];
    /**
     * Teachers模型对象
     * @var \app\admin\model\classes\Teachers
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\classes\Teachers;
        $stu_model = new \app\admin\model\classes\Student;

        $this->view->assign("isCaptainList", $this->model->getIsCaptainList());
        $this->view->assign("genderdataList", $stu_model->getGenderdataList());




    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        $admin_id = $this->auth->id;
        $adming_where=[];
        if (!$this->auth->isSuperAdmin()) {
            $adming_where['fa_classes_teacher.admin_id'] = $admin_id;
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)->where($adming_where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");

            $admin = Db::name('admin')->where('username',$params['mobile'])->find();
            if(!empty($admin))
            {
                $this->error('账号已存在');
            }

            Db::startTrans();
            try {

                $udata['username'] = $params['mobile'];
                $udata['mobile'] = $params['mobile'];
                $udata['nickname'] = $params['realname'];
                $udata['salt'] = Random::alnum();
                $udata['password'] = md5(md5($params['password']) . $udata['salt']);
                if(empty($params['avatar']))
                {
                    $avatar = '/assets/img/avatar.png';
                }
                else
                {
                    $avatar = $params['avatar'];
                }
                $udata['createtime'] = time();
                $udata['avatar'] = $avatar;
                $admin_id = Db::name('admin')->insertGetId($udata);
                $data = [
                    'uid' => $admin_id,
                    'group_id' => 3
                ];
                Db::name('auth_group_access')->insert($data);
                $tdata = [
                    'user_id' => $admin_id,
                    'realname' => $params['realname'],
                    'mobile' => $params['mobile'],
                    'gender' => $params['gender'],
                    'iscaptain' => $params['iscaptain'],
                    'avatar' => $avatar,
                    'admin_id' => $this->auth->id,
                    'createtime' => time(),
                ];
                Db::name('classes_teacher')->insert($tdata);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success();
        }
        return $this->view->fetch();
    }
    public function edit($ids = null)
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");

            Db::startTrans();
            try {
                $tlist = Db::name('classes_teacher')->find($ids);
                $ulist = Db::name('admin')->find($tlist['user_id']);

                $udata['username'] = $params['mobile'];
                $udata['mobile'] = $params['mobile'];
                $udata['nickname'] = $params['realname'];
                if(!empty($params['password']))
                {
                    $udata['password'] = md5(md5($params['password']) . $ulist['salt']);
                }
                if(empty($params['avatar']))
                {
                    $avatar = '/assets/img/avatar.png';
                }
                else
                {
                    $avatar = $params['avatar'];
                }
                $udata['avatar'] = $avatar;
                $udata['updatetime'] = time();
                Db::name('admin')->where('id',$ulist['id'])->update($udata);
                $tdata = [
                    'realname' => $params['realname'],
                    'mobile' => $params['mobile'],
                    'gender' => $params['gender'],
                    'iscaptain' => $params['iscaptain'],
                    'avatar' => $avatar,
                    'updatetime' => time(),
                ];
                Db::name('classes_teacher')->where('profile_id',$tlist['profile_id'])->update($tdata);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success();
        }
        $row = Db::name('classes_teacher')->find($ids);
        $this->view->assign('row',$row);
        return $this->view->fetch();
    }
}
